package io.zcoder.innoway.activities;

import android.os.Bundle;
import android.support.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.UserResponse;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.EditTextCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class ChangePassWordActivity extends BaseActivity {

    @BindView(R.id.pass)
    EditTextCustom mPassOld;
    @BindView(R.id.pass_1)
    EditTextCustom mPass1;
    @BindView(R.id.pass_2)
    EditTextCustom mPass2;

    @OnClick(R.id.change)
    void onChange() {
        validate();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_change_password_activity);
        ButterKnife.bind(this);
        setTitle(getString(R.string.change_password));
        showBack(true);
    }

    private void validate() {
        if (mPassOld.isEmpty() || mPass1.isEmpty() || mPass2.isEmpty()) {
            showAlert(getString(R.string.error), getString(R.string.error_empty));
            return;
        }
        if (!mPass1.getText().toString().equalsIgnoreCase(mPass2.getText().toString()) || mPass1.getText().length() < 6) {
            showAlert(getString(R.string.error), getString(R.string.error_pass));
            return;
        }
        changePassWord();
    }

    private void changePassWord() {
        showProgress();
        RestClient.build(this, true).changePassword(PrefUtils.getInt(this, PrefUtils.PREF_USER_ID), mPassOld.getString(), mPass1.getString(), new Callback<UserResponse>() {
            @Override
            public void success(UserResponse userResponse, Response response) {
                hideProgress();
                if (userResponse.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), userResponse.getMessage());
                } else if (userResponse.getData() != null) {
                    PrefUtils.setString(ChangePassWordActivity.this, PrefUtils.PREF_AUTHEN_TOKEN, userResponse.getData().getAuth_token());
                    finish();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }
}
